<?php
namespace app\admin\controller;
use app\admin\model\Member;
use \app\admin\controller\BaseController;
use \app\admin\model\Shop;
use \app\admin\model\ShopImage;
use \app\admin\model\Categroy;
use \app\admin\model\CategroySpecification;
use app\admin\model\ShopSpecification;
use \think\Request;
use think\Db;

class Goods extends BaseController
{
	/**
	 * 首页
	 * @param  Shop   $shop [description]
	 * @return [type]       [description]
	 */
	protected $member_id;
	protected $auth_name;
	protected $where;
	public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->member_id =  session('member_id');
        $this->auth_name = session('auth_name');
        if($this->auth_name  == 'member'){
            $this->where = ['member_id' => $this->member_id];
        }else{
            $this->where = [ ];
        }
    }

    public function index(Shop $shop)
	{
		$this->isLogin();
        $list = $this->defaut($shop);
		if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where($this->where)->where('shop_delete',0)->paginate(10);
		    if(count($result) == 0)  $this->error('您所搜索的商品不存在');
        }else{
            $result = $shop->where('shop_delete',0)->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
		$page = $result->render();
		return view('goods/index', compact('list', 'result', 'page'));
	}
	/**
	 * 审核商品
	 * @param  Shop   $shop [description]
	 * @return [type]       [description]
	 */
	public function shop_audit(Shop $shop)
	{
        $this->isLogin();
		$list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('audit',0)->where($this->where)->where('shop_delete',0)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的审核商品不存在');
        }else{
            $result = $shop->where(['audit' => 0, 'shop_delete' => 0])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
		$page = $result->render();
		return view('goods/shop_audit', compact('list', 'result', 'page'));
	}
	/**
	 * 上架商品
	 * @param  Shop   $shop [description]
	 * @return [type]       [description]
	 */
	public function shop_use(Shop $shop)
	{
        $this->isLogin();
		$list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('is_use',0)->where('audit',1)->where($this->where)->where('shop_delete',0)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的上架商品不存在');
        }else {
            $result = $shop->where(['is_use' => 0,'audit'=>1,  'shop_delete' => 0])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
        $page = $result->render();
		return view('goods/shop_use', compact('list', 'result', 'page'));
	}
	/**
	 * 下架商品
	 * @param  Shop   $shop [description]
	 * @return [type]       [description]
	 */
	public function shop_no_use(Shop $shop)
	{
        $this->isLogin();
		$list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('is_use',1)->where($this->where)->where('shop_delete',0)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的下架商品不存在');
        }else{
            $result = $shop->where(['is_use' => 1, 'audit' => 1, 'shop_delete' => 0])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
		$page = $result->render();
		return view('goods/shop_no_use', compact('list', 'result', 'page'));
	}
	/**
	 * 删除商品
	 * @param  Shop   $shop [description]
	 * @return [type]       [description]
	 */
	public function shop_delete(Shop $shop)
	{
        $this->isLogin();
		$list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('shop_delete',1)->where($this->where)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的删除商品不存在');
        }else{
            $result = $shop->where([ 'shop_delete' => 1])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
        $page = $result->render();
		return view('goods/shop_delete', compact('list', 'result', 'page'));
	}
    /**
     *热销商品
     * @param Shop $shop
     * @return \think\response\View|void
     */
	public function shop_hot(Shop $shop)
    {
        $this->isLogin();
        $list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('is_heat',1)->where($this->where)->where('shop_delete',0)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的热销商品不存在');
        }else{
            $result = $shop->where(['is_use'=>0,'audit'=>1,'shop_delete'=>0,'is_heat' => 1])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
        $page = $result->render();
        return view('goods/shop_hot',compact('list','result','page'));
    }
    /**
     * 优选商品
     * @param Shop $shop
     * @return \think\response\View|void
     */
	public function shop_pref(Shop $shop)
    {
        $this->isLogin();
        $list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('preferred',1)->where($this->where)->where('shop_delete',0)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的优选商品不存在');
        }else{
            $result = $shop->where(['is_use'=>0,'audit'=>1,'shop_delete'=>0, 'preferred' => 1])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
        $page = $result->render();
        return view('goods/shop_pref',compact('list','result','page'));
    }
    /**
     * 推荐商品
     * @param Shop $shop
     * @return \think\response\View|void
     */
	public function shop_new(Shop $shop)
    {
        $this->isLogin();
        $list = $this->defaut($shop);
        if(input('search')){
            $result = $shop->where('shop_name',input('search'))->where('is_new',1)->where($this->where)->where('shop_delete',0)->paginate(10);
            if(count($result) == 0) $this->error('您所搜索的推荐商品不存在');
        }else {
            $result = $shop->where([ 'is_use'=>0,'audit'=>1,'shop_delete'=>0,'is_new' => 1])->where($this->where)->order('create_time desc')->paginate(10); //分页
        }
        $page = $result->render();
        return view('goods/shop_new',compact('list','result','page'));
    }
	/**
	 * 获取商品的图片
	 * @param  [type] $shop_id [description]
	 * @return [type]          [description]
	 */
	public function getShopImage($shop_id)
	{
        $this->isLogin();
		$shop_image = new ShopImage();
		$result = $shop_image->where(['shop_id' => $shop_id, 'is_use' => 0])->select()->toArray();
		if($result) {
			return $result[0]['image_path'];
		} else {
			return '';
		}
	}
	/**
	 * 审核
	 * @param  [type] $audit [description]
	 * @param  [type] $id    [description]
	 * @return [type]        [description]
	 */
	public function audit(Shop $shop,$audit, $id)
	{
        $this->isLogin();
        $post['audit'] = $audit;
		$result = $shop->where(['id' => $id])->where($this->where)->where('shop_delete',0)->update($post);
		if($result){
            $recode = $shop->where('id',$id)->update(['is_use'=>0,'is_use_time'=>time()]);
            if(!$recode) $this->error('商品上架失败');
			return $this->redirect($_SERVER["HTTP_REFERER"]);
		} else {
			return $this->error('操作失败，请联系管理员');
		}
	}
	/**
	 * 删除
	 * @param  [type] $shop_delete [description]
	 * @param  [type] $id          [description]
	 * @return [type]              [description]
	 */
	public function delete(Shop $shop,$shop_delete, $id)
	{
        $this->isLogin();
        if($shop_delete == '1'){
            $post['shop_delete'] = $shop_delete;
            $post['is_new'] = 0;
            $post['is_heat'] = 0;
            $post['preferred'] = 0;
            $post['spike'] = 0;
        }
        $post['shop_delete'] = $shop_delete;
		$result = $shop->where(['id' => $id])->where($this->where)->update($post);
		if($result){
			$this->redirect($_SERVER["HTTP_REFERER"]);
		} else {
			$this->error('操作失败，请联系管理员');
		}

	}
	/**
	 * 下架 上架
	 * @param  [type] $shop_delete [description]
	 * @param  [type] $id          [description]
	 * @return [type]              [description]
	 */
	public function isUse(Shop $shop, $id)
	{
        $this->isLogin();
        $is_use = input('is_use');
        if($is_use == '1'){
            $data['is_use'] = $is_use;
            $data['is_new'] = 0;
            $data['is_heat'] = 0;
            $data['preferred'] = 0;
            $data['spike'] = 0;
        }elseif($is_use == '0'){
            $data['is_use'] = $is_use;
        }
		$result = $shop->where(['id' => $id])->update($data);
		if($result){
			$this->redirect($_SERVER["HTTP_REFERER"]);
		} else {
			$this->error('操作失败，请联系管理员');
		}
	}
	/**
	 * 热销
	 * @param  [type] $shop_delete [description]
	 * @param  [type] $id          [description]
	 * @return [type]              [description]
	 */
	public function heat(Shop $shop)
	{
        $this->isLogin();
	    $is_heat = input('is_heat');
		$post['is_heat'] = $is_heat;
		$res = $shop->where('is_use',0)->where('audit',1)->where('shop_delete',0)->where('is_heat',1)->where($this->where)->count();
		if((intval($res) < 200 && $is_heat == 1) || $is_heat == 0 ){
            $result = $shop->where(['id' => input('id')])->update($post);
            if($result){
                return $this->redirect($_SERVER["HTTP_REFERER"]);
            } else {
                return $this->error('操作失败，请联系管理员');
            }
        }
        return $this->error('热销商品超出上限，操作失败');

	}
	/**
	 * 推荐
	 * @param  [type] $shop_delete [description]
	 * @param  [type] $id          [description]
	 * @return [type]              [description]
	 */
	public function new(Shop $shop)
	{
        $this->isLogin();
        $is_new = input('is_new');
		$post['is_new'] = $is_new;
        $res = $shop->where('is_use',0)->where('audit',1)->where('shop_delete',0)->where('is_new',1)->where($this->where)->count();
        if((intval($res) < 6 && $is_new == 1) || $is_new == 0 ){
            $result = $shop->where(['id' => input('id')])->update($post);
            if($result){
                $this->redirect($_SERVER["HTTP_REFERER"]);
            } else {
                $this->error('操作失败，请联系管理员');
            }
        }
        return $this->error('推荐商品超出上限，操作失败');

	}
	/**
	 * 优选
	 * @param  [type] $shop_delete [description]
	 * @param  [type] $id          [description]
	 * @return [type]              [description]
	 */
	public function preferred(Shop $shop)
	{
        $this->isLogin();
        $preferred = input('preferred');
        $categroy_id = input('categroy_id');
		$post['preferred'] = $preferred;
        $res = $shop->where('is_use',0)->where('audit',1)->where('shop_delete',0)->where('categroy_id',$categroy_id)->where('preferred',1)->where($this->where)->count();
        if((intval($res) < 8 && $preferred == 1) || $preferred == 0 ){
            $result = $shop->where(['id' => input('id')])->update($post);
            if($result){
                return $this->redirect($_SERVER["HTTP_REFERER"]);
            } else {
                return $this->error('操作失败，请联系管理员');
            }
        }
        return $this->error('该类优选商品超出上限，操作失败');
	}
	/**
	 * 获取首页展示数量
	 * @param  [type] $user [description]
	 * @return [type]       [description]
	 */
	public function defaut($shop)
	{
        $this->isLogin();
        $list['shop_count'] = $shop->where('shop_delete',0)->where($this->where)->count();//全部商品
        $list['shop_audit'] = $shop->where(['audit' => 0, 'shop_delete' => 0])->where($this->where)->count(); //审核商品
        $list['shop_use'] = $shop->where([ 'is_use' => 0, 'audit' => 1,'shop_delete' => 0])->where($this->where)->count(); //上架
        $list['shop_no_use'] = $shop->where([ 'is_use' => 1,'audit' => 1, 'shop_delete' => 0])->where($this->where)->count(); //下架
        $list['shop_delete'] = $shop->where([ 'shop_delete' => 1])->where($this->where)->count(); //回收站
        $list['shop_pref'] = $shop->where(['is_use' => 0,'preferred' => 1,'audit' => 1, 'shop_delete' => 0])->where($this->where)->count(); //优选商品
        $list['shop_hot'] = $shop->where(['is_use' => 0,'is_heat' => 1,'audit' => 1, 'shop_delete' => 0])->where($this->where)->count(); //热销商品
        $list['shop_new'] = $shop->where(['is_use' => 0,'is_new' => 1,'audit' => 1, 'shop_delete' => 0])->where($this->where)->count(); //推荐商品
		return $list;
	}
	/**
	 * 渲染添加商品界面
	 * @return [type] [description]
	 */
	public function insert()
	{
        $this->isLogin();
		return view('', compact(''));
	}
    /**
     * 渲染添加商品分类
     * @param Categroy $categroy
     * @return mixed|string
     */
	public function getGoodsCate(Categroy $categroy)
    {
        $this->isLogin();
        $type = input('post.type');
        $categroy_id = input('post.categroy');
        if(!$type) {
            $result = $categroy->where(['pid' => 0, 'is_use' => 0, 'grade' => 1])->select()->toArray();
        } else if ($type == '1') {
            $result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 2])->select()->toArray();
        } else {
            $result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 3])->select()->toArray();
        }
       if(!$result){
            return $this->setError('暂无数据');
       }
        return json_encode($result,  JSON_UNESCAPED_UNICODE);
    }
    /**
     * 图片上传
     * @param $name
     * @param $files
     * @return mixed
     */
    public function upload($files)
    {
        $this->isLogin();
        if(is_array($files)){
            foreach($files as $file){
                $info = $file->validate(['size' => 10485760])->move('upload');
                if($info) $image[] = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
            }
            return $image;
        }else if(is_object($files) && count($files)==1){
            $info = $files->validate(['size' => 10485760])->move('upload');
            if($info){
                return  $image = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
            }
            return  $files->getError();// 上传失败获取错误信息
        }
        else{
            return $this->error('请选择图片');
        }
    }
    /**
     * 商品添加时获取展示分类规格
     * @param CategroySpecification $spec
     * @return \think\response\Json
     */
    public function getCategroySpec(CategroySpecification $spec)
    {
        $this->isLogin();
        if(!request()->isPost()){
            return json(['code'=>100,'mes'=>'参数不能为空']);
        }
        $specs = $spec->where('categroy_id',input('categroy'))->select();
        if(empty($spec)){
            return json(['code'=>300,'msg'=>'该分类暂无规格']);
        }
        return json($specs);
    }
    /**
     * 商品添加
     * @param Shop $shop
     * @param ShopImage $shopImage
     */
    public function addShop(Shop $shop)
    {
        $this->isLogin();
        Db::startTrans();
        try{
            $shop_mark = implode(',',$_POST['shop_mark']);
            //字段验证
            $shop_files =  request()->file('image_path'); //商品橱窗图片
            $image_path = $this->upload($shop_files);
            $data = Request::instance()->except('member_phone,banner_path,detail_path,spec,/admin/goods/addshop_html');
            $data['member_id'] = session('member_id');
            $result = $shop->goodsSave($data,$shop_mark,$image_path); //添加商品信息到shop表
            if($result['valid'] == '2'){
                throw new \Exception('同分类不能重复添加同名商品');
            }elseif($result['valid'] == '1'){
                throw new \Exception('商品信息添加失败');
            }elseif($result['valid'] == '0'){
                throw new \Exception($result['message']);
            }
            //添加商品图片
            $id = $shop->getLastInsID(); //获取最后一次shop表插入的数据的id
            //添加商品橱窗图片到shop_image表
            $recode = $this->imageAdd($id,$image_path,0);
            if(!$recode){
                throw new \Exception('商品橱窗图上传错误');
            }
            //添加商品轮播图片到shop_image表
            $banner_files = request()->file('banner_path');
            $banner_path = $this->upload($banner_files);
            $banner = $this->imageAdd($id,$banner_path,1);
            if(!$banner){
                throw new \Exception('商品轮播图上传错误');
            }
            //添加商品详情图片到shop_image表
            $details_files = request()->file('detail_path');
            $details_path = $this->upload($details_files); //调取update处理图片
            $detail = $this->imageAdd($id,$details_path,2);
            if(!$detail){
                throw new \Exception('商品轮播图上传错误');
            }
            //添加商品规格
            $string = $_POST['spec'];  //商品规格打包的字符串
            $categroy_id = input('categroy_id');  //三级分类id
            $shopSpec = $this->shopSpecAdd($string,$id,$categroy_id);
            if(!$shopSpec){
                throw new \Exception('商品规格添加错误');
            }
            Db::commit();
        }catch(\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getmessage());
        }
        return $this->success('商品添加成功','admin/goods/index');
    }
    //循环添加商品橱窗图、轮播图、详情图
    public function imageAdd($id,$image_path,$type)
    {
        $this->isLogin();
        if($type == 1){
            //轮播图
            foreach($image_path as $key => $value){
                $result = new ShopImage();
                $data['shop_id'] = $id;
                $data['staff'] = 1;
                $data['create_time'] = time();
                $data['image_path'] = $value;
                $recode = $result->save($data);
            }
        }else if($type == 2){
            //详情图
            foreach($image_path as $key => $value) {
                $result = new ShopImage();
                $data['shop_id'] = $id;
                $data['staff'] = 2;
                $data['create_time'] = time();
                $data['image_path'] = $value;
                $recode = $result->save($data);
            }
        }else{
            //商品橱窗图
            $result = new ShopImage();
            $data['shop_id'] = $id;
            $data['create_time'] = time();
            $data['image_path'] = $image_path;
            $recode = $result->save($data);
        }
        return $recode;
    }
    /**
     * 循环添加商品规格
     * @param $string
     * @param $shop_id
     * @param $categroy_id
     * @return false|int
     */
    public function shopSpecAdd($string,$shop_id,$categroy_id)
    {
        $this->isLogin();
        $array =  explode(",",$string);
        foreach($array as $value){
            $result =  explode('|&|',$value);
            $data['shop_id'] = $shop_id;
            $data['categroy_id'] = $categroy_id;
            $shop = new Shop();
            $good = $shop->where('id',$data['shop_id'])->field('stock_num')->find();
            $stock_num = $good['stock_num'];
            if(count($result) == 4 && $result[2] != 0){
                $data['spec_one_name'] = $result[0];
                $data['spec_two_name'] = $result[1];
                $data['stock_num'] = $result[2];
                $data['warning_num'] = $result[3];
            }elseif(count($result) == 3 && $result[1] != 0){
                $data['spec_one_name'] = $result[0];
                $data['stock_num'] = $result[1];
                $data['warning_num'] = $result[2];
            }else{
                continue;
            }
            $stock_num += $data['stock_num'];
            $shop->where('id',$data['shop_id'])->update(['stock_num'=>$stock_num]); //所有商品总库存写入shop表
            $specDb = new ShopSpecification();
            $specResult =$specDb->save($data);
        }
        return $specResult;
    }
    //商品编辑之展示模板页面
    public function updateShopShow(Shop $shop,ShopImage $shopImage,Categroy $categroy)
    {
        $this->isLogin();
        $shop_id = input('shop_id');
        $categroy_id = input('categroy_id');
        $goods = $shop->where('id',$shop_id)->select()->toArray();  //获取商品基本信息
        $image_path = $shopImage->where('shop_id',$shop_id)->where('staff',0)->field('id,image_path')->find(); //获取商品橱窗图
        $banners = $shopImage->where('shop_id',$shop_id)->where('staff',1)->field('id,image_path')->select()->toArray(); //获取商品banner图
        $cateThree = $categroy->where('id',$categroy_id)->field('categroy_name,pid')->find();
        $cateTwo = $categroy->where('id',$cateThree['pid'])->field('categroy_name,pid')->find();
        $cateOne = $categroy->where('id',$cateTwo['pid'])->field('categroy_name,pid')->find();
        $cates = $cateOne['categroy_name'] .'>'. $cateTwo['categroy_name'] .'>'. $cateThree['categroy_name'];
        return view('goods/updateGood',compact('goods','image_path','banners','cates'));
    }
    /**
     * 商品编辑之获取分类展示（一级二级三级）
     * @param Categroy $categroy
     * @return mixed|string
     */
    public function getCategroys(Categroy $categroy)
    {
        $this->isLogin();
        $type = input('post.type');
        $categroy_id = input('post.categroy');
        if(!$type) {
            $result = $categroy->where(['pid' => 0, 'is_use' => 0, 'grade' => 1])->select()->toArray();
        } else if ($type == '1') {
            $result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 2])->select()->toArray();
        } else {
            $result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 3])->select()->toArray();
        }
        if(!$result){
            return $this->setError('暂无数据');
        }
        return json_encode($result,  JSON_UNESCAPED_UNICODE);

    }
    /**
     * 商品编辑之规格展示（前端）
     * @param CategroySpecification $categroySpecification
     * @param ShopSpecification $shopSpecification
     * @return \think\response\Json
     */
    public function getGoodsSpec(CategroySpecification $categroySpecification,ShopSpecification $shopSpecification)
    {
        $this->isLogin();
        $shop_id = input('shop_id');
        $categroy_id = input('categroy_id');
        $Spec['cate'] = $categroySpecification->where('categroy_id',$categroy_id)->field('spec_name')->select()->toArray();
        $Spec['shop'] = $shopSpecification->where('shop_id',$shop_id)->where('categroy_id',$categroy_id)->where('is_delete',0)->select()->toArray();
        return json($Spec);
    }
    /**
     * 商品橱窗图、banner图处理
     * @return string
     */
    public function pictureHandle()
    {
        $this->isLogin();
        $shop_image = request()->file('image');
        if($shop_image){
            return $this->picture($shop_image);
//            dump($this->picture($shop_image));
        }
        die;
    }
    public function picture($file)
    {
        $this->isLogin();
        $info = $file->validate(['size' => 10485760])->move('upload');
        if($info) {
            $image = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
            return $image;
        }
    }
    /**
     * 商品编辑之获取商品详情图接口
     * @param ShopImage $shopImage
     * @return \think\response\Json
     */
    public function detailPicture(ShopImage $shopImage)
    {
        $this->isLogin();
        $shop_id = input('shop_id');
        $details = $shopImage->where('shop_id',$shop_id)->where('staff',2)->where('is_use',0)->select();
        return json($details);
    }
    /**
     * 商品编辑之获取商品标识接口
     * @param Shop $shop
     * @return \think\response\Json
     */
    public function shopMark(Shop $shop)
    {
        $this->isLogin();
        $shop_id = input('shop_id');
        $marks = $shop->where('id',$shop_id)->field('shop_mark')->find()->toArray();
        return json($marks);
    }
    /**
     * 商品编辑保存
     * @param Shop $shop
     */
    public function updateSave(Shop $shop,ShopImage $shopImage)
    {
        $this->isLogin();
        Db::startTrans();
        try{
            $categroy_id = input('categroy_id');
            $categroyId = input('categroyId');
            $data = Request::instance()->except('member_phone,shop_id,categroy_id,categroyId,banner,image,detail,spec,/admin/goods/updatesave_html');
            $data['image_path'] =  input('image'); //商品橱窗图片
            $data['member_id'] = session('member_id');
            $data['update_time'] = time();
            $data['shop_mark'] = implode(',',$data['shop_mark']);
            $data['money_diff'] =  intval($data['shop_start_money']) - intval($data['shop_end_money']) ;
            $data['categroy_id'] = input('categroyId');
            if($categroy_id){
                $data['categroy_id'] = $categroy_id;
                $data['id'] = input('shop_id');
                $res = $shop->where('categroy_id',$categroy_id)->where('shop_name',$data['shop_name'])->count();
                if($res) {
                    throw new \Exception('该分类已有该商品');
                }
                $result = $shop->where('id',input('shop_id'))->where('categroy_id',$categroyId)->update($data); //添加商品信息到shop表
            }else{
                $data['categroy_id'] = input('categroyId');
                $data['id'] = input('shop_id');
                $result = $shop->where('id',$data['id'])->where('categroy_id',$categroyId)->update($data); //添加商品信息到shop表
            }
            if(!$result){
                throw new \Exception('商品信息编辑失败');
            }
            //添加商品橱窗图片到shop_image表
            $id = input('shop_id');
            $image_path = input('image');
            $shop_image = $this->getShopImageHandle($id,$image_path);
            if(!$shop_image){
                throw new \Exception('商品橱窗图编辑错误');
            }
            //添加商品轮播图片到shop_image表
            $banner_path = $_POST['banner'];
            $banner_image = $this->getBannerHandle($banner_path,$id);
            if(!$banner_image){
                throw new \Exception('商品轮播图编辑错误');
            }
            //添加商品详情图片到shop_image表
            $details_path = $_POST['detail'];
            $tail = $this->getDetailHandle($details_path,$id,$shopImage);
            if(!$tail){
                throw new \Exception('商品详情图编辑错误或添加错误');
            }
            //添加商品规格
            $string = $_POST['spec'];  //商品规格打包的字符串
            if($categroy_id){
                $shopSpec = $this->shopSpecUpdate($string,$id,$categroy_id);
            }else{
                $shopSpec = $this->shopSpecUpdate($string,$id,$categroyId);
            }
            if(!$shopSpec){
                throw new \Exception('商品规格编辑错误');
            }
        Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            return $this->error($e->getmessage());
        }
        return  $this->success('商品编辑成功','admin/goods/index');
    }
    /**
     * 商品编辑之商品橱窗图片处理
     * @param $id
     * @param $image_path
     * @param $type
     * @return $this
     */
    public function getShopImageHandle($id,$image_path)
    {
        $this->isLogin();
        //商品橱窗图
        $result = new ShopImage();
        $data['update_time'] = time();
        $data['image_path'] = $image_path;
        $res = $result->where('shop_id',$id)->where('staff',0)->update($data);
        return $res;
    }
    /**
     * 商品编辑之保存商品规格
     * @param $string
     * @param $shop_id
     * @param $categroy_id
     * @return $this
     */
    public function shopSpecUpdate($string,$shop_id,$cate_id)
    {
        $this->isLogin();

        $array =  explode(",",$string);
        $specModel = new ShopSpecification();
        $specs = $specModel->where('shop_id',$shop_id)->field('id,shop_id')->select()->toArray();
        foreach($specs as $value){
            $shopSpecification = new ShopSpecification();
            $specDel = $shopSpecification->where('id',$value['id'])->where('shop_id',$shop_id)->update(['is_delete'=>1,'delete_time'=>time()]);
        }
        if(!$specDel) throw new \Exception('规格删除错误');
        foreach($array as $value){
            $result =  explode('|&|',$value);
            $data['categroy_id'] = $cate_id;
            $data['shop_id'] = $shop_id;
            if(count($result) == 4 && $result[2] != 0){
                $data['spec_one_name'] = $result[0];
                $data['spec_two_name'] = $result[1];
                $data['stock_num'] = $result[2];
                $data['warning_num'] = $result[3];
            }
            $shopSpecification = new ShopSpecification();
            $specResult = $shopSpecification->save($data);
        }
        return $specResult;
    }

//        if(count($specDate) > count($specs)){
//            $updateData = array_slice($specDate, 0, count($specs));
//            $saveData = array_slice($specDate,  count($specs));
//                $upDate = [];
//                foreach($updateData as $key => $value){
//                    foreach($specs as $k => $v){
//                        $updateData[$key]['id'] = $specs[$key]['id'];
//                    }
//                    $val = implode(';',$updateData[$key]);
//                    dump($val);
//                    if(in_array($val,$specArray)){
//                        continue;
//                    }
//                    $val = explode(';',$val);
//                    if(!empty($val)){
//                        $upDate['categroy_id'] = $val[0];
//                        $upDate['shop_id'] = $val[1];
//                        $upDate['spec_one_name'] = $val[2];
//                        $upDate['spec_two_name'] = $val[3];
//                        $upDate['stock_num'] = $val[4];
//                        $upDate['warning_num'] = $val[5];
//                        $upDate['id'] = $val[6];
//                    }
//                    dump($upDate);
////                    $shopSpecification = new ShopSpecification();
////                    $res =$shopSpecification->where('id',$upDate['id'])->where('shop_id',$shop_id)->update($upDate);
//                }
//                die;
//            foreach($saveData as $value){
//                    $shopSpecification = new ShopSpecification();
//                    $result =$shopSpecification->save($value);
//                }
//        }elseif(count($specDate) < count($specs)){
//            $updateData = array_slice($specs, 0, count($specDate));
//            $deteleData = array_slice($specs,  count($specDate));
//            foreach($specDate as $key =>$value){
//                foreach($updateData as $k => $v){
//                    $specDate[$key]['id'] = $updateData[$key]['id'];
//                }
//                $shopSpecification = new ShopSpecification();
//                $res =$shopSpecification->where('id',$specDate[$key]['id'])->where('shop_id',$shop_id)->update($specDate[$key]);
//            }
//            foreach($deteleData as $value){
//                $shopSpecification = new ShopSpecification();
//                $result =$shopSpecification->where('id',$value['id'])->delete();
//            }
//        }elseif(count($specDate) == count($specs)){
//            $shopSpecs = $specDb->where('shop_id',$shop_id)->field('categroy_id,shop_id,spec_one_name,spec_two_name,stock_num,warning_num,id')->select()->toArray();
//            $shopData = [];
//            //将$shopSpecs用‘/’链接成字符串
//            foreach($shopSpecs as $v){
//                $shopData[] = implode(';',$v);
//            }
//            //将查到的规格id循环添加到$specDate中
//            foreach($specDate as $key => $value) {
//                foreach ($specs as $k => $v) {
//                    $specDate[$key]['id'] = $specs[$key]['id'];
//                }
//            }



//    public function specHandle($result,$shop_id,$cate_id)
//    {
//        if (count($result) == 4 && $result[3] != 0) {
//            $handleData['categroy_id'] = $cate_id;
//            $handleData['shop_id'] = $shop_id;
//            $handleData['id'] = $result[0];
//            $handleData['spec_one_name'] = $result[1];
//            $handleData['spec_two_name'] = $result[2];
//            $handleData['stock_num'] = $result[3];
//            $handleData['warning_num'] = $result[4];
//        }
//        return $handleData;
//    }
    /**
     * 商品编辑之获取商品分类规格
     * @param Categroy $categroy
     * @return mixed|string
     */
    public function getCateSpec(CategroySpecification $spec)
    {
        $this->isLogin();
        if(!request()->isPost()){
            return json(['code'=>100,'mes'=>'参数不能为空']);
        }
        $specs = $spec->where('categroy_id',input('categroy'))->select();
        if(empty($spec)){
            return json(['code'=>300,'msg'=>'该分类暂无规格']);
        }
        return json($specs);
    }
    /**
     * 商品编辑之banner图片处理
     * @param $banner_path
     * @return $this
     */
    public function getBannerHandle($banner_path)
    {
        $this->isLogin();
        $banner_data = [];
        foreach($banner_path as $banner){
            $result = explode(';',$banner);
            $banner_data['id'] = $result[0];
            $banner_data['image_path'] = $result[1];
            $banner_data['update_time'] = time();
            $shopImage = new ShopImage();
            $res = $shopImage->where('id',$banner_data['id'])->where('staff',1)->update($banner_data);
        }
        return $res;
    }
    /**
     * 编辑之详情图处理
     * @param $details_path
     * @param $id
     * @return int
     */
    public function getDetailHandle($details_path,$id,$shopImage)
    {
        $this->isLogin();
        //过滤空值
        $details = [];
        foreach ($details_path as $key => $value) {
            if (!empty($value)) $details[] = $value;
        }
        $new = [];
        $detailData = [];
        foreach ($details as $image) {
            $image = explode(';', $image);
            if ($image[0] == 'new') {
                $new['shop_id'] = $id;
                $new['image_path'] = $image[1];
                $new['create_time'] = time();
                $new['staff'] = 2;
                $shopImage = new ShopImage();
                $detailResult = $shopImage->save($new);
            } elseif ($image[1] == 'del') {
                $image_id = $image[0];
                $shopImage = new ShopImage();
                $detailResult = $shopImage->where('id', $image_id)->update(['is_use' => 1,'update_time'=>time()]);
            } else {
                $image = implode(';', $image);
                $detailData[] = $image;
            }
        }
        if (!empty($detailData)) {
            $detailImages = $shopImage->where('shop_id', $id)->where('staff', 2)->field('id,image_path')->select()->toArray();  //查出该商品的所有详情图地址
            $detailArray = [];
            $detailImages = array_column($detailImages, 'image_path', 'id');  //数据处理成key 为id ，value 为 image_path;
            foreach ($detailImages as $key => $value) {
                $detailArray[] = $key . ';' . $value;
            }
            foreach ($detailData as $value) {
                if (in_array($value, $detailArray)) {
                    continue;
                }
                $upData[] = explode(';', $value);
            }
            if (!empty($upData)) {
                $detailResult = $this->detailUpDatabase($upData, $id);
            } else {
                $detailResult = 1;
            }
        }
        return $detailResult;
    }
    public function detailUPDatabase($upData,$id){
        $data = [];
        foreach($upData as $value){
            $data['id'] = $value[0];
            $data['image_path'] = $value[1];
            $data['update_time'] = time();
            $shopImage = new ShopImage();
            $upResult = $shopImage->where('id',$data['id'])->where('shop_id',$id)->update($data);
        }
        return $upResult;
    }
    public function hotWord()
    {
        return view('goods/hotword');
    }
}
